package com.iary.application.impl;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.iary.application.TbShopService;
import com.taobao.api.ApiException;
import com.taobao.api.DefaultTaobaoClient;
import com.taobao.api.TaobaoClient;
import com.taobao.api.domain.Shop;
import com.taobao.api.request.ShopGetRequest;
import com.taobao.api.response.ShopGetResponse;

public class TbShopServiceImpl implements TbShopService {

	private static final Logger log = LoggerFactory
			.getLogger(TbShopServiceImpl.class);

	private String appKey;
	private String appSecret;
	private String appUrl;
	private Long appPid;
	private String appNick;

	TbShopServiceImpl() {
	}

	public TbShopServiceImpl(String appKey, String appSecret, String appUrl,
			String appPid, String appNick) {
		this.appKey = appKey;
		this.appSecret = appSecret;
		this.appUrl = appUrl;
		this.appPid = Long.valueOf(appPid);
		this.appNick = appNick;
	}

	@Override
	public Shop getShopByNick(String nick) {
		Shop result = null;
		if(StringUtils.isBlank(nick)){
			return result;
		}
		TaobaoClient client = new DefaultTaobaoClient(appUrl, appKey, appSecret);
		ShopGetRequest req = new ShopGetRequest();
		req.setFields("sid,cid,title,nick,desc,bulletin,pic_path,created,modified");
		req.setNick(nick);
		try {
			ShopGetResponse response = client.execute(req);
			if (response.isSuccess()) {
				result = response.getShop();
			} else {
				log.warn(
						"ShopGetRequest failure, code:{}, msg:{}",
						response.getErrorCode(), response.getMsg());
				log.warn(
						"ShopGetRequest failure, subCode:{}, subMsg:{}",
						response.getSubCode(), response.getSubMsg());
			}
		} catch (ApiException e) {
			log.error("ShopGetRequest error", e);
		}
		return result;
	}

}
